package com.tp;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.MediaColumns;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PostComment extends CustomWindow {
	static String name;
	static int id;
	static int icon_;
	static int type;
	static int selectPosition; // luu vi tri cua Trip dc chon
	static int selectDayPosition_; // luu ngay cua Trip dc chon
	TextView obj;
	static int id_TripDetail, id_TripDetailRes, id_TripDetailEvent;
	private static final int PICK_IMAGE = 1;
	private static final int CAMERA_REQUEST = 1888;
	public ImageView imageView, iconView;
	public String path_capture;
	public String filePath;
	public EditText comment;
	ImageButton change, delete;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post_comment);
		this.icon.setImageResource(R.drawable.modify);
		this.title.setText("Bình luận, Thêm ảnh");
		obj = (TextView) findViewById(R.id.post_locationName);
		if (name != null)
			obj.setText(name);
		if (Add.objName != null && Add.flag == 1) {
			obj.setText(Add.objName.getText());
			Add.flag = 0;
		}
		comment = (EditText) findViewById(R.id.comment);

		imageView = (ImageView) findViewById(R.id.image);
		iconView = (ImageView) findViewById(R.id.icon_);
		if (icon_ != 0)
			iconView.setImageResource(icon_);
		// openOptionsMenu();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_post_comment, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onAttachedToWindow()
	 */
	@Override
	public void onAttachedToWindow() {
		// TODO Auto-generated method stub
		// super.onAttachedToWindow();
		openOptionsMenu();
	}

	/*
	 * @Override public void onWindowFocusChanged(boolean hasFocusFlag) {
	 * super.onWindowFocusChanged(hasFocusFlag); if (hasFocusFlag) {
	 * openOptionsMenu(); } }
	 */
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.edit:
			Add._name = name;
			Add.id_Obj = id;
			Add.flag = 1;
			startActivity(new Intent(this, Add.class));
			return true;
		case R.id.up_photo:
			String types[] = { "Bộ sưu tập", "Chụp ảnh" };
			String title = "Thêm ảnh";
			DialogCustomize dia = new DialogCustomize();
			dia.a(this, types, title);
			break;
		case R.id.post_comment:

			if (comment.getText().toString().equals(""))
				Toast.makeText(this, "Nhập bình luận của bạn",
						Toast.LENGTH_SHORT).show();
			else {
				addComment();
				comment.setText("");
			}
			break;
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.view.View.OnClickListener#onClick(android.view.View)
	 */

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			Trip.selectPosition = selectPosition; // quay lai dung Trip hien tai
			Trip.selectDayPosition_ = selectDayPosition_;
			Intent a = new Intent(this, Trip.class);
			// a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(a);
			return true;
		}
		return false;
	}

	// xu ly up anh. Copy ben Add
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		int rotate = 0;
		switch (requestCode) {
		case CAMERA_REQUEST: // capture photo
			if (resultCode == RESULT_OK) {
				Log.v("CAPTURE", "OK");
				String[] paths = { "/mnt/sdcard/DCIM/Camera" };
				String[] mediaType = { "image/jpeg" };
				MediaScannerConnection.scanFile(this, paths, mediaType, null);
				sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
						Uri.parse("file://"
								+ Environment.getExternalStorageDirectory())));

				ExifInterface exif;
				try {
					exif = new ExifInterface(DialogCustomize.fileName);

					int orientation = exif.getAttributeInt(
							ExifInterface.TAG_ORIENTATION,
							ExifInterface.ORIENTATION_NORMAL);

					switch (orientation) {
					case ExifInterface.ORIENTATION_ROTATE_270:
						rotate = 270;

						break;
					case ExifInterface.ORIENTATION_ROTATE_180:
						rotate = 0;

						break;
					case ExifInterface.ORIENTATION_ROTATE_90:
						rotate = 90;

						break;
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				File photos = new File(DialogCustomize.fileName);
				Log.v("imageFilePath", DialogCustomize.fileName);
				filePath = savePhotoToServer(DialogCustomize.fileName);
				Matrix matrix = new Matrix();
				matrix.postRotate(rotate);
				Bitmap b = decodeFile(photos);
				b = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b.getHeight(),
						matrix, true);
				imageView.setImageBitmap(b);
				addPhoto();

			} else
				Log.v("CAPTURE", "FAIL");
			break;
		case PICK_IMAGE: // choose from sdcard

			if (resultCode == Activity.RESULT_OK) {

				Uri _uri = data.getData();
				Log.v("uri", _uri.toString());
				if (_uri != null) {
					// User had pick an image.
					Cursor cursor = this.getContentResolver().query(_uri,
							new String[] { MediaColumns.DATA }, null, null,
							null);
					cursor.moveToFirst();

					// Link to the image
					String imageFilePath = cursor.getString(0);
					Log.v("imageFilePath", imageFilePath);
					filePath = savePhotoToServer(imageFilePath);
					File photos = new File(imageFilePath);
					Bitmap b = decodeFile(photos);
					b = Bitmap.createScaledBitmap(b, 150, 150, true);
					imageView.setImageBitmap(b);
					cursor.close();
					addPhoto();
				}
			}

			break;

		default:
		}

	}

	static Bitmap decodeFile(File f) {

		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);

			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 700;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale++;
			}

			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;

	}

	public String getRealPathFromURI(Uri contentUri) {
		try {
			String[] proj = { MediaColumns.DATA };
			Cursor cursor = managedQuery(contentUri, proj, null, null, null);
			int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		} catch (Exception e) {
			return contentUri.getPath();
		}
	}

	public String savePhotoToServer(String pathToOurFile) {
		HttpURLConnection connection = null;
		DataOutputStream outputStream = null;
		// DataInputStream inputStream = null;

		// String pathToOurFile = "/data/file_to_send.mp3";
		String urlServer = Constant.host + "/PhotoController/savePhoto";
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		String result = null;
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;

		try {
			FileInputStream fileInputStream = new FileInputStream(new File(
					pathToOurFile));

			URL url = new URL(urlServer);
			connection = (HttpURLConnection) url.openConnection();

			// Allow Inputs & Outputs
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);

			// Enable POST method
			connection.setRequestMethod("POST");

			connection.setRequestProperty("Connection", "Keep-Alive");
			connection.setRequestProperty("Content-Type",
					"multipart/form-data;boundary=" + boundary);

			outputStream = new DataOutputStream(connection.getOutputStream());
			outputStream.writeBytes(twoHyphens + boundary + lineEnd);
			outputStream
					.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
							+ pathToOurFile + "\"" + lineEnd);
			outputStream.writeBytes(lineEnd);
			bytesAvailable = fileInputStream.available();
			bufferSize = Math.min(bytesAvailable, maxBufferSize);
			buffer = new byte[bufferSize];

			// Read file
			bytesRead = fileInputStream.read(buffer, 0, bufferSize);

			while (bytesRead > 0) {
				outputStream.write(buffer, 0, bufferSize);
				bytesAvailable = fileInputStream.available();
				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);
			}

			outputStream.writeBytes(lineEnd);
			outputStream.writeBytes(twoHyphens + boundary + twoHyphens
					+ lineEnd);

			// Responses from the server (code and message)
			int serverResponseCode = connection.getResponseCode();
			if (serverResponseCode == 200) {
				BufferedReader br = new BufferedReader(new InputStreamReader(
						connection.getInputStream()));
				StringBuilder sb = new StringBuilder();
				String line;
				while ((line = br.readLine()) != null) {
					sb.append(line + "\n");
				}
				br.close();
				result = sb.toString();

			}
			// String serverResponseMessage = connection.getResponseMessage();
			Log.v("SYSTEM", result);
			fileInputStream.close();
			outputStream.flush();
			outputStream.close();

		} catch (Exception ex) {
			// Exception handling
		}
		return result;
	}

	public void addPhoto() {
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_User", Integer
				.toString(Constant.user)));
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id)));
		postParameters.add(new BasicNameValuePair("path", filePath));
		String result = null;
		try {

			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/PhotoController/addPhoto", postParameters);
			String res = result.toString();
			res = res.replaceAll("\\s+", "");
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Add photo successful", Toast.LENGTH_SHORT)
						.show();
			} else
				Toast.makeText(this, "Add photo fail", Toast.LENGTH_SHORT)
						.show();
		} catch (Exception e) {
		}

	}

	public void addComment() {
		ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
		postParameters.add(new BasicNameValuePair("id_User", Integer
				.toString(Constant.user)));
		postParameters.add(new BasicNameValuePair("id_Obj", Integer
				.toString(id)));
		postParameters.add(new BasicNameValuePair("content", comment.getText()
				.toString()));
		String result = null;
		try {

			result = CustomHttpClient.executeHttpPost(Constant.host
					+ "/CommentController/addComment", postParameters);
			String res = result.toString();
			res = res.replaceAll("\\s+", "");
			if (Integer.parseInt(res) > 0) {
				Toast.makeText(this, "Add comment successful",
						Toast.LENGTH_SHORT).show();
			} else
				Toast.makeText(this, "Add comment fail", Toast.LENGTH_SHORT)
						.show();
		} catch (Exception e) {
		}

	}
}
